package com.lavegue.webaction;

import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.regex.Pattern;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;

import com.lavegue.common.Constants;
import com.lavegue.common.ListAction;
import com.lavegue.model.ManageMsg;
import com.lavegue.model.ManageMsgDetail;
import com.lavegue.model.Msg;
import com.lavegue.model.MsgDetail;
import com.lavegue.model.UserInfo;
import com.lavegue.service.AreaService;
import com.lavegue.service.BisTypeService;
import com.lavegue.service.ManageMsgService;
import com.lavegue.service.MsgService;
import com.lavegue.service.TopUpService;
import com.lavegue.service.UserInfoService;
import com.lavegue.util.FileCharsetDetector;
import com.lavegue.util.MsgSender;
import com.lavegue.util.StringUtil;

/**
 * author: tinazhifen
 * description:
 *
 */
public class MsgAction extends ListAction<Msg> {
	//短信价格
	public static final BigDecimal SM_PRICE = new BigDecimal("0.3");
	private static final int RANDOM_MAX = 4;
	private static final String MUBAN_KEY = "send_msg";
	private static final String RECEIVE = "msg_receives";
	private String likeName;
	private MsgService msgService;
	private BisTypeService bisTypeService;
	private List listType;
	private int msgTypeId;
	private int mubanId;
	private File receice;
	private int first;
	private String receiceContentType;
	//自定义内容
	private String txt;
	//接受者，自己输入那种
	private String receiceStr;
	private ManageMsg mubanMsg;
	private ManageMsgService manageMsgService;
	private UserInfoService userInfoService;
	private List<ManageMsg> randonMsgs;
	private AreaService areaService;
	private TopUpService topUpService;
	//根据彩信标题和内容
   public String findMsg()
	{
	   System.out.println(msgTypeId);
		System.out.println(likeName);
		pageObj=msgService.findMsgByContent(pageNo, pageSize,msgTypeId,likeName);
		return "listMsg";
	}
	
	public String showTop()
	{
		listType=bisTypeService.findAll();
		return "top";
	}
	
	//20120131 修改[ 注册页面使用这个顶部页面]
	public String showTopReg()
	{
		listType=bisTypeService.findAll();
		return "topReg";
	}
	
	/**
	 * 进入发送界面
	 * @return
	 */
	public String sendPage() { 
		if (this.getSessionUser() == null) {
			return G_LOGIN_PAGE; 
		}
		if (first > 0) {
			this.removeSession("msg_txt_tmp");
			this.mubanMsg = manageMsgService.findById(mubanId);
			ManageMsgDetail d = this.mubanMsg.getManageMsgDetails().get(0);
			if (!StringUtil.isEmpty(d.getTxt())) {
				this.setSessionAtrribute("msg_txt_tmp", d.getTxt());
			}
			this.setSessionAtrribute(MUBAN_KEY, this.mubanMsg);
			this.removeSession(RECEIVE);
		} else {
			this.mubanMsg = (ManageMsg) this.getSessionAtrribute(MUBAN_KEY);
			this.setSessionAtrribute(MUBAN_KEY, this.mubanMsg);
		}
		randonMsgs= manageMsgService.findRandomList(RANDOM_MAX);
		return "sendMsgPage";
	}
	
	/**
	 * 清楚接收者
	 * @return
	 */
	public String cleanReceive() {
		if (this.getSessionUser() == null) {
			return G_LOGIN_PAGE;
		}
		this.setSessionAtrribute(RECEIVE, null);
		this.addActionMessage("清除成功");
		return sendPage();
	}
	
	/**
	 * 上传接受者
	 * @return
	 * @throws Exception 
	 */
	public String uploadReceive() throws Exception {
		if (this.getSessionUser() == null) {
			return G_LOGIN_PAGE;
		}
		List<String> receivers = new ArrayList<String>();
		if (this.receice != null) {
			if (!this.receiceContentType.equals("text/plain")) {
				this.addActionError("上传的文件类型有误");
				return sendPage();
			}
			FileCharsetDetector fcd = new FileCharsetDetector();
			String encoding = fcd.guestFileEncoding(this.receice);
			if (encoding == null) {
				receivers = FileUtils.readLines(receice);
			} else {
				receivers = FileUtils.readLines(receice, encoding);
			}
			receivers = StringUtil.cutEmptyEl(receivers);
		}
		checkReceive(receivers);
		if (!hasErrors()) {
			this.setSessionAtrribute(RECEIVE, receivers);
		}
		mubanMsg = (ManageMsg) this.getSessionAtrribute(MUBAN_KEY);
		mubanMsg.setTitle(likeName.trim());
		if (mubanMsg.getBisType().getEditAble() == mubanMsg.EDIT_ENABLE) {
			ManageMsgDetail detail = mubanMsg.getManageMsgDetails().get(0);
			detail.setTxt(txt.trim());
			this.setSessionAtrribute("msg_txt_tmp",  txt);
		}
		return sendPage();
	}
	
	public String editTxt() {
		String[] arr = this.receiceStr.split("\r\n");
		List<String> list = new ArrayList<String>();
		for (String string : arr) {
			if (!StringUtil.isEmpty(string)) {
				list.add(string);
			}
		}
		checkReceive(list);
		if (!hasErrors()) {
			this.setSessionAtrribute(RECEIVE, list);
		}
		mubanMsg = (ManageMsg) this.getSessionAtrribute(MUBAN_KEY);
		mubanMsg.setTitle(likeName.trim());
		if (mubanMsg.getBisType().getEditAble() == mubanMsg.EDIT_ENABLE) {
			ManageMsgDetail detail = mubanMsg.getManageMsgDetails().get(0);
			detail.setTxt(txt.trim());
			this.setSessionAtrribute("msg_txt_tmp",  txt);
		}
		return sendPage();
	}
	
	public String sendMsg()  throws Exception  {
		if (this.getSessionUser() == null) {
			return G_LOGIN_PAGE;
		}
		this.setSessionAtrribute("msg_txt_tmp",  txt);
		ManageMsg mubanMsg = (ManageMsg) this.getSessionAtrribute(MUBAN_KEY);
		Msg msg = new Msg();
		mubanMsg.setTitle(likeName);
		
		UserInfo userinfo = userInfoService.findById(this.getSessionUser().getId());
		List<String> receivers = new ArrayList<String>();
		if (this.receice != null) {
			if (!this.receiceContentType.equals("text/plain")) {
				this.addActionError("上传的文件类型有误");
				return sendPage();
			}
			FileCharsetDetector fcd = new FileCharsetDetector();
			String encoding = fcd.guestFileEncoding(this.receice);
			if (encoding == null) {
				receivers = FileUtils.readLines(receice);
			} else {
				receivers = FileUtils.readLines(receice, encoding);
			}
			
		}
		if (receivers == null || receivers.isEmpty()) {
			receivers = (List<String>) this.getSessionAtrribute(RECEIVE);
		}
		
		//检查内容
		if ((receivers == null || receivers.isEmpty()) && this.getSessionAtrribute(RECEIVE) ==null) {
			this.addActionError("请输入接收者号码");
			return sendPage();
		} else {
			receivers = StringUtil.cutEmptyEl(receivers);
			checkReceive(receivers);
			if (this.hasErrors()) {
				return sendPage();
			}
		}
		//最后的接受者列表
		List<String> rcs2 = new ArrayList<String>();
		for (int i = 0; i < receivers.size(); i++) {
			String r = receivers.get(i);
			if (!StringUtil.isEmpty(r)) {
				rcs2.add(r.trim());
			}
		}
		if (userinfo.getMsgCnt() < rcs2.size()) {
			this.addActionError("发送失败，余额不足");
			return sendPage();
		}
		
		msg.setTitle(likeName);
		List<MsgDetail> msgDetails = new ArrayList<MsgDetail>();
		//设置msg信息
		msg.setGroup(mubanMsg.getBisGroup());
		msg.setPrice(SM_PRICE);
		msg.setSender(getSessionUser());
		msg.setSendTime(new Date());
		//msg.setTitle(mubanMsg.getTitle());
		msg.setType(mubanMsg.getBisType());
		msg.setId(null);
		
		if (mubanMsg.getBisType().getEditAble() == mubanMsg.EDIT_ENABLE) {
			List<ManageMsgDetail> details = mubanMsg.getManageMsgDetails();
			ManageMsgDetail detail = details.get(0);
			if (!StringUtil.isEmpty(this.txt)) {
				detail.setTxt(this.txt.trim());
			}
			MsgDetail msgdetail = new MsgDetail(); 
			msgdetail.setId(null);
			BeanUtils.copyProperties(msgdetail, detail);
			msgDetails.add(msgdetail);
			msgDetails.add(genPersonInfo());
		} else {
			List<ManageMsgDetail> details = mubanMsg.getManageMsgDetails();
			for (ManageMsgDetail d : details) {
				MsgDetail msgdetail = new MsgDetail();
				BeanUtils.copyProperties(msgdetail, d);
				msgdetail.setId(null);
				msgDetails.add(msgdetail);
			}
			msgDetails.add(genPersonInfo());
			Collections.sort(msgDetails);
		}
		msg.setMsgDetails(msgDetails);
		MsgSender sender = new MsgSender(this.getProjectPath());
		List<String> sendMsgResult = sender.sendMsg(msg, rcs2);
		//插入信息表
		for (String mobileNo : sendMsgResult) {
			Msg copyMsg = copyMsg(msg);
			copyMsg.setRecever(mobileNo);
			msgService.save(copyMsg);
		}
		UserInfo newUser = userInfoService.findById(this.getSessionUser().getId());
		this.setSessionAtrribute(Constants.SESSION_USER, newUser);
		this.removeSession("msg_txt_tmp");
		this.removeSession(MUBAN_KEY);
		this.removeSession(RECEIVE);
		return "sendSuccess"; 
	}
	
	private Msg copyMsg(Msg msg) {
		Msg newMsg = new Msg();
		newMsg.setGroup(msg.getGroup());
		newMsg.setPrice(msg.getPrice());
		newMsg.setRecever(msg.getRecever());
		newMsg.setSender(msg.getSender());
		newMsg.setSendTime(msg.getSendTime());
		newMsg.setTitle(msg.getTitle());
		newMsg.setType(msg.getType());
		List<MsgDetail> msgDetails2 = msg.getMsgDetails();
		List<MsgDetail> msgDetailsNew = new ArrayList<MsgDetail>();
		for (MsgDetail md : msgDetails2) {
			MsgDetail newMd = new MsgDetail();
			newMd.setInter(md.getInter());
			if (newMd.getInter() == null) {
				newMd.setInter(0);
			}
			newMd.setMsg(newMsg);
			newMd.setMusic(md.getMusic());
			newMd.setPic(md.getPic());
			newMd.setTxt(md.getTxt());
			newMd.setZhenNo(md.getZhenNo());
			md.setId(null);
			msgDetailsNew.add(newMd);
		}
		newMsg.setMsgDetails(msgDetailsNew);
		
		return newMsg;
	}
	
	private MsgDetail genPersonInfo() throws IOException {
		String huanhang = "   ";
		MsgDetail d = new MsgDetail();
		d.setZhenNo(6);
		UserInfo user = this.userInfoService.findById(this.getSessionUser().getId());
		d.setInter(0);
		StringBuffer sb = new StringBuffer();
		String filename = Constants.MSG_MOBAN_PIC_PATH + FilenameUtils.getName(user.getPersonalIco());
		if (!StringUtil.isEmpty(user.getPersonalIco())) {
			FileUtils.copyFile(new File(this.getProjectPath() + user.getPersonalIco()), 
					new File(this.getProjectPath()+ filename));
			d.setPic(filename);
		}
		sb.append("姓名：" + user.getUserName() + huanhang);
		sb.append("所在地区：" + getAreaString(user) + huanhang);
		sb.append("所在公司：" + user.getCompany().getCompanyName() + huanhang);
		sb.append("手机号码：" +  user.getAccount() + huanhang);
		if (!StringUtil.isEmpty(user.getEmail())) {
			sb.append("电子邮箱：" + user.getEmail() + huanhang);
		}
		if (!StringUtil.isEmpty(user.getQq())) {
			sb.append("QQ号码：" + user.getQq() + huanhang);
		}
		sb.append("个人主页：" + user.getPersonalHonepage() +huanhang);
		if (!StringUtil.isEmpty(user.getPersonalIntro())) {
			sb.append("个人介绍：" + user.getPersonalIntro());
		}
		d.setTxt(sb.toString());
		return d;
	}
	
	private void checkReceive(List<String> rs) {
		 // /^((13[0-9]{1}|15[0-9]{1}|18[0-9]{1}|)+\d{8})$/
		Pattern pattern = Pattern.compile("^((13[0-9]{1}|15[0-9]{1}|18[0-9]{1}|)+\\d{8})$");
		   // return pattern.matcher(str).matches();    
			for (String s : rs) {
				if (!StringUtil.isEmpty(s)) {
					if(!pattern.matcher(s.trim()).matches() || s.length()!=11) {
						this.addActionError(s + "：非有效手机号码，请更正");
						return;
					}
				}
			}
	}
	
	private String getAreaString(UserInfo user) {
		StringBuffer sb = new StringBuffer();
		if(!StringUtil.isEmpty(user.getProvince())) {
			sb.append(areaService.findById(Integer.valueOf(user.getProvince())).getName() + " ");
		}
		if(!StringUtil.isEmpty(user.getCity())) {
			sb.append(areaService.findById(Integer.valueOf(user.getCity())).getName() + " ");
		}
		if(!StringUtil.isEmpty(user.getZone())) {
			sb.append(areaService.findById(Integer.valueOf(user.getZone())).getName() + " ");
		}
		return sb.toString();
	}
	
	public String yulan() {
		String huanhang = "\r\n";
		if (this.getSessionUser() == null) {
			return G_LOGIN_PAGE;
		}
		ManageMsg msg = (ManageMsg) this.getSessionAtrribute(MUBAN_KEY);
		if (msg.getBisType().getEditAble() == msg.EDIT_ENABLE) {
			//对于可编辑只有一帧
			List<ManageMsgDetail> details = msg.getManageMsgDetails();
			for (ManageMsgDetail d : details) {
				d.setTxt(this.txt);
			}
		}
		
		if (this.getSessionUser() != null && msg.getManageMsgDetails().get((msg.getManageMsgDetails().size() -1)).getZhenNo() != null) {
			StringBuffer sb = new StringBuffer();
			sb.append("姓名：" + this.getSessionUser().getUserName() + huanhang);
			sb.append("所在地区：" + getAreaString(this.getSessionUser()) + huanhang);
			sb.append("所在公司：" + this.getSessionUser().getCompany().getCompanyName() + huanhang);
			sb.append("手机号码：" + this.getSessionUser().getAccount() + huanhang);
			if (!StringUtil.isEmpty(this.getSessionUser().getEmail())) {
				sb.append("电子邮箱：" + this.getSessionUser().getEmail() + huanhang);
			}
			if (!StringUtil.isEmpty(this.getSessionUser().getQq())) {
				sb.append("QQ号码：" + this.getSessionUser().getQq() + huanhang);
			}
			if (!StringUtil.isEmpty(this.getSessionUser().getPersonalHonepage())) {
				sb.append("个人主页：" + this.getSessionUser().getPersonalHonepage() + huanhang);
			}
			if (!StringUtil.isEmpty(this.getSessionUser().getPersonalIntro())) {
				sb.append("个人介绍：" + this.getSessionUser().getPersonalIntro() + huanhang);
			}
			ManageMsgDetail dl = new ManageMsgDetail();
			UserInfo ui = this.userInfoService.findById(this.getSessionUser().getId());
			dl.setPic(ui.getPersonalIco());
			dl.setTxt(sb.toString());
			msg.getManageMsgDetails().add(dl);
		}
		this.mubanMsg =  msg;
		return "yulanMsg";
	}
	
	
	public List<ManageMsg> getRandonMsgs() {
		return randonMsgs;
	}

	public void setRandonMsgs(List<ManageMsg> randonMsgs) {
		this.randonMsgs = randonMsgs;
	}

	public AreaService getAreaService() {
		return areaService;
	}

	public void setAreaService(AreaService areaService) {
		this.areaService = areaService;
	}

	public UserInfoService getUserInfoService() {
		return userInfoService;
	}

	public void setUserInfoService(UserInfoService userInfoService) {
		this.userInfoService = userInfoService;
	}

	public int getMubanId() {
		return mubanId;
	}
	
	public File getReceice() {
		return receice;
	}
	
	public int getFirst() {
		return first;
	}

	public void setFirst(int first) {
		this.first = first;
	}

	public void setReceice(File receice) {
		this.receice = receice;
	}

	public String getReceiceContentType() {
		return receiceContentType;
	}

	public void setReceiceContentType(String receiceContentType) {
		this.receiceContentType = receiceContentType;
	}

	public String getTxt() {
		return txt;
	}

	public void setTxt(String txt) {
		this.txt = txt;
	}

	public String getReceiceStr() {
		return receiceStr;
	}

	public void setReceiceStr(String receiceStr) {
		this.receiceStr = receiceStr;
	}

	public ManageMsg getMubanMsg() {
		return mubanMsg;
	}

	public void setMubanMsg(ManageMsg mubanMsg) {
		this.mubanMsg = mubanMsg;
	}

	public ManageMsgService getManageMsgService() {
		return manageMsgService;
	}

	public void setManageMsgService(ManageMsgService manageMsgService) {
		this.manageMsgService = manageMsgService;
	}

	public void setMubanId(int mubanId) {
		this.mubanId = mubanId;
	}

	public String getLikeName() {
		return likeName;
	}
	public void setLikeName(String likeName) {
		this.likeName = likeName;
	}
	public MsgService getMsgService() {
		return msgService;
	}
	public void setMsgService(MsgService msgService) {
		this.msgService = msgService;
	}

	public BisTypeService getBisTypeService() {
		return bisTypeService;
	}

	public void setBisTypeService(BisTypeService bisTypeService) {
		this.bisTypeService = bisTypeService;
	}

	public List getListType() {
		return listType;
	}

	public void setListType(List listType) {
		this.listType = listType;
	}

	public int getMsgTypeId() {
		return msgTypeId;
	}

	public void setMsgTypeId(int msgTypeId) {
		this.msgTypeId = msgTypeId;
	}

	public TopUpService getTopUpService() {
		return topUpService;
	}

	public void setTopUpService(TopUpService topUpService) {
		this.topUpService = topUpService;
	}
}

